package com.lishe.lishe.lishe.module.launch.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.AppManager;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.launch.adapter.ViewPagerAdapter;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;

/**
 * Created by zhcase on 2017/9/5.
 * 启动是的导航页
 */

public class LaunchActivity extends Activity implements View.OnClickListener {

    private ViewPager mViewPager;
    private int[] mImageList = {R.mipmap.splash_1, R.mipmap.splash_2, R.mipmap.splash_3};

    private ImageView mIvLaunch;
    private TextView mTvCountDown;
    private CountDownTimer mTimer;

    private int mDistance;
    private View mDotsLayout;
    private LinearLayout mIn_ll;
    private ImageView mLight_dots;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_launch);
        initView();
        if (getSharePreferences()) {//首次登陆
            setSharePreferences();
            addDots();
            moveDots();
            initViewPage();
        } else {
            mViewPager.setVisibility(View.GONE);
            mDotsLayout.setVisibility(View.GONE);
            mIvLaunch.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(Globals.getToken())) {
                doTokenLogin();
            }
            intoMain();
        }
    }

    private void initView() {
        mIn_ll = findViewById(R.id.in_ll);
        mDotsLayout = findViewById(R.id.rl_dots);
        mLight_dots = findViewById(R.id.iv_light_dots);

        mViewPager = findViewById(R.id.view_pager);
        mIvLaunch = findViewById(R.id.launch_image);
        mViewPager = findViewById(R.id.view_pager);
        mTvCountDown = findViewById(R.id.countdown);
        mTvCountDown.setOnClickListener(this);
    }

    /**
     * 登陆
     */
    private void doTokenLogin() {
        String token = Globals.getToken();
        HttpUser.getUpToken(token, null, responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            Log.e("跟新token", data);
            if (data != null) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                        String mtoken = jsonObject.optString("data");
                        String msg = jsonObject.optString("msg");
                        if (!TextUtils.isEmpty(mtoken) && !mtoken.equals("null")) {
                            LogUtil.e("清空保存token", mtoken);
                            SharedPreferencesUtils.saveToken(mtoken, LaunchActivity.this);
                        } else {
                            LogUtil.e("清空token", mtoken);
                            SharedPreferencesUtils.removeToken(LaunchActivity.this);
                        }
                    } else {
                        Log.e("清空token", "");
                        SharedPreferencesUtils.removeToken(LaunchActivity.this);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    SharedPreferencesUtils.removeToken(LaunchActivity.this);
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            SharedPreferencesUtils.removeToken(LaunchActivity.this);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        hideBottomUIMenu();
    }

    //这里是加载mipmap中图片的方式，初始化ViewPager及其图片资源
    private void initViewPage() {
        List<View> viewList = new ArrayList<>();
        LayoutInflater inflater = getLayoutInflater().from(this);
        View view;
        for (int i = 0; i < mImageList.length; i++) {
            if (i == mImageList.length - 1) {
                view = inflater.inflate(R.layout.guide_lastview, null);
                view.findViewById(R.id.enter).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(LaunchActivity.this, MainActivity0.class));
                    }
                });
                ImageView image = view.findViewById(R.id.Image);
                Glide.with(LaunchActivity.this).asGif().load(mImageList[i]).into(image);
            } else {
                view = inflater.inflate(R.layout.guide_view, null);
                ImageView image = view.findViewById(R.id.Image);
                Glide.with(LaunchActivity.this).asGif().load(mImageList[i]).into(image);
            }
            viewList.add(view);
        }
        mViewPager.setAdapter(new ViewPagerAdapter(viewList));
    }

    private void intoMain() {
        mTvCountDown.setVisibility(View.VISIBLE);
        Glide.with(LaunchActivity.this).asGif().load(R.mipmap.launch_new).into(mIvLaunch);
        mTimer = new CountDownTimer(3200, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTvCountDown.setText("跳过 " + millisUntilFinished / 1000 );
            }

            @Override
            public void onFinish() {
                mTvCountDown.setText("跳过 " + 0);
                startActivity(new Intent(LaunchActivity.this, MainActivity0.class));
                //overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
            }
        };
        mTimer.start();
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.countdown:
                startActivity(new Intent(LaunchActivity.this, MainActivity0.class));
                //overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                if (mTimer != null) {
                    mTimer.cancel();
                    mTvCountDown.setVisibility(View.GONE);
                }
                break;
        }
    }

    /**
     * 对首次登录进行记录
     */
    private void setSharePreferences() {
        SharedPreferences firstLogin = getSharedPreferences(Globals.SHAREPREFERENCES_USER, MODE_PRIVATE);
        SharedPreferences.Editor ed = firstLogin.edit();
        ed.putBoolean("isFirstLogin", false);
        ed.commit();
    }

    private boolean getSharePreferences() {
        boolean isFirstLogin;
        SharedPreferences firstLogin = getSharedPreferences(Globals.SHAREPREFERENCES_USER, MODE_PRIVATE);
        isFirstLogin = firstLogin.getBoolean("isFirstLogin", true);
        LogUtil.i("首次登陆", isFirstLogin + "");
        return isFirstLogin;
    }

    private void addDots() {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getResources().getDimensionPixelOffset(R.dimen.dp_6), getResources().getDimensionPixelOffset(R.dimen.dp_6));
        layoutParams.setMargins(0, 0, 40, 0);
        for (int i = 0; i < mImageList.length; i++) {
            ImageView dot = new ImageView(this);
            dot.setImageResource(R.mipmap.point_unselected);
            mIn_ll.addView(dot, layoutParams);
        }
    }

    private void moveDots() {
        mLight_dots.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (mIn_ll.getChildCount() < 2) return;
                //获得两个圆点之间的距离
                mDistance = mIn_ll.getChildAt(1).getLeft() - mIn_ll.getChildAt(0).getLeft();
                mLight_dots.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //页面滚动时小白点移动的距离，并通过setLayoutParams(params)不断更新其位置
                /*float leftMargin = mDistance * (position + positionOffset);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLight_dots.getLayoutParams();
                params.leftMargin = (int) leftMargin;
                mLight_dots.setLayoutParams(params);
                if(position == mPicList.size() - 1){
                    mDotsLayout.setVisibility(View.GONE);
                }
                if(position != mPicList.size() - 1){
                    mDotsLayout.setVisibility(View.VISIBLE);
                }*/
            }

            @Override
            public void onPageSelected(int position) {
                //页面跳转时，设置小圆点的margin
                float leftMargin = mDistance * position;
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLight_dots.getLayoutParams();
                params.leftMargin = (int) leftMargin;
                mLight_dots.setLayoutParams(params);
                if(position == mImageList.length - 1){
                    mDotsLayout.setVisibility(View.GONE);
                }
                if(position != mImageList.length - 1){
                    mDotsLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {}
        });
    }

}
